package com.basin.auth.core.component;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.basin.auth.common.entity.AuthAccount;
import com.basin.auth.common.form.SignUpForm;
import com.basin.auth.core.repository.AuthAccountRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 * @date: 2025/3/30 22:03
 * @description:
 */
@Component
@RequiredArgsConstructor
public class BasinSysRegister {
    private final AuthAccountRepository repository;

    /**
     * @description: register
     * @param: signUpForm - [SignUpForm]
     * @return: {@link boolean}
     * @author: Sammy ZHONG | sammy1997@aliyun.com
     * @date: 2025/3/30 22:12
     */
    public boolean register(SignUpForm signUpForm) {
        String pinyinName = PinyinUtil
                .getPinyin(signUpForm.getName().toLowerCase(Locale.ROOT))
                .replaceAll(" ", "");
        // 数据库是否存在
        long count = repository.count(Wrappers.<AuthAccount>lambdaQuery()
                .eq(AuthAccount::getUsername, pinyinName));
        AuthAccount account = new AuthAccount() {{
            // ex: zhangsan1
            setUsername(count > 0 ? pinyinName + count : pinyinName);
            setPassword("123456");
        }};
        return this.repository.save(account);
    }
}
